<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
// import { ElTag } from 'element-plus'
import { Table } from '@/components/Table'
import { Icon } from '@/components/Icon'
import { getTableListApi, saveTableApi, delTableListApi,saveScoreApi } from '@/api/project'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/project/types'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import BacthUpdate from './components/BacthUpdate.vue'
import AccountList from './components/AccountList.vue'

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getTableListApi({
      page: unref(currentPage),
      pagesize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.items,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    setTimeout(() => {
      saveLoading.value = false
      dialogVisible.value = false
    }, 1000)
    getList()
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('project.id'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          return (
            <div 
              style="
                color: #409eff; 
                cursor: pointer; 
                width: 100%;
                height: 100%;
                padding: 8px;
                margin: -8px;
                align-items: center;
                transition: background-color 0.2s;
              "
              onMouseenter={(e: MouseEvent) => {
                const target = e.target as HTMLElement
                if (target) {
                  target.style.backgroundColor = '#f5f7fa'
                }
              }}
              onMouseleave={(e: MouseEvent) => {
                const target = e.target as HTMLElement
                if (target) {
                  target.style.backgroundColor = 'transparent'
                }
              }}
              onClick={() => action(data.row, 'edit')}
            >
              {data.row.id}
            </div>
          )
        }
      }
    }
  },
  {
    field: 'search',
    hidden: true,
    label: t('tableGroupManager.search'),
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input',
      hidden: true,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'symbol',
    label: t('project.name'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'airdropTime',
    label: t('project.utime'),
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      colProps: {
        span: 24
      },
      componentProps: {
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        format: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'price',
    label: t('project.price'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          // 保留2位小数但不四舍五入的函数
          const truncateToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            // 将数字乘以100，向下取整，再除以100，实现截断而非四舍五入
            return (Math.floor(numValue * 100) / 100).toFixed(2)
          }
          return (
            // <div style="position: relative; width: 100%; text-align: left;">
            <div>
              <span>{truncateToTwoDecimals(data.row.price)}</span>
            </div>
          )
        }
      }
    }
  },
  {
    field: 'accs',
    label: t('project.accountNum'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      hidden: true,
      colProps: {
        span: 24
      }
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          return (
            <div 
              style="
                color: #409eff; 
                cursor: pointer; 
                width: 100%;
                height: 100%;
                align-items: center;
                transition: background-color 0.2s;
              "
              onMouseenter={(e: MouseEvent) => {
                const target = e.target as HTMLElement
                if (target) {
                  target.style.backgroundColor = '#f5f7fa'
                }
              }}
              onMouseleave={(e: MouseEvent) => {
                const target = e.target as HTMLElement
                if (target) {
                  target.style.backgroundColor = 'transparent'
                }
              }}
              onClick={() => accountList(data.row, 'accountList')}
            >
              {Array.isArray(data.row.accs) ? data.row.accs.length : 0}
            </div>
          )
        }
      }
    }
  },
  {
    field: 'remarks',
    label: t('project.remarks'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('project.bacthUpdate'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton type="primary" onClick={() => bacthUpdate(data.row, 'bacthUpdate')}>
                <Icon icon="ep:edit" />
              </BaseButton>
              {/* <BaseButton type="success" onClick={() => action(data.row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(data.row)}>
                {t('exampleDemo.del')}
              </BaseButton> */}
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogBacthVisible = ref(false)
const dialogAccountListVisible = ref(false)

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const bacthUpdate = (row: TableData, type: string) => {
  dialogTitle.value = t('project.bacthUpdate')
  currentRow.value = row
  dialogBacthVisible.value = true
  actionType.value = 'bacthUpdate'
}

const delLoading = ref(false)

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const accountList = (row: TableData, type: string) => {
  dialogTitle.value = `<span style="color: #409eff;">${row.symbol}</span>参与账号详情`
  actionType.value = type
  currentRow.value = row
  dialogAccountListVisible.value = true
}
const action = (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()
const BacthUpdateRef = ref<ComponentRef<typeof BacthUpdate>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveTableApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
const bacth = async () => {
  const write = unref(BacthUpdateRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveScoreApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogBacthVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(currentRow)">
        {{ t('exampleDemo.del') }}
      </BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total,
        layout: '->, total, sizes, prev, pager, next, jumper'
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :maxHeight="250">
    <Write
      v-if="actionType === 'edit' || actionType === 'add'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />
    <BacthUpdate
      v-if="actionType === 'bacthUpdate'"
      ref="BacthUpdateRef"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
  <Dialog v-model="dialogBacthVisible" :title="dialogTitle" width="600px" :maxHeight="400">
    <BacthUpdate
      v-if="actionType === 'bacthUpdate'"
      ref="BacthUpdateRef"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="bacth"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogBacthVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
    <Dialog v-model="dialogAccountListVisible" :title="dialogTitle" width="600px" :maxHeight="400">
    <AccountList
      v-if="actionType === 'accountList'"
      ref="accountList"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />
  </Dialog>
</template>